'use strict';

const BaseService = require('./base.js')
const modelName = 'Email';
const nodemailer = require("nodemailer");
const dayjs = require("dayjs");
const transporter = nodemailer.createTransport({
  host: "smtp.exmail.qq.com",
  port: 465,
  secure: true, // true for port 465, false for other ports
  auth: {
    user: "Support@tasyachttrip.com.au",
    pass: "120120Zed",
  },
});

class EmailService extends BaseService {
  constructor(ctx) {
    super(ctx, modelName);
  }

  async sendEmail({ id }) {
    let order = await this.ctx.service.order.findOne(id)
    let template = await this.ctx.model.EmailTemplate.findOne({
      where: {
        lang: order.lang || 'en'
      }
    })
    console.log('template',template.lang,order.lang)
    if (!template) {
      return this.create({
        order_no: order.order_no,
        subject: '邮件发送失败',
        content: '邮件发送失败，未创建模版',
        to: order.contact_email,
        lang: order.lang
      })
    }
    if (!order.contact_email) {
      return this.create({
        order_no: order.order_no,
        subject: '邮件发送失败',
        content: '邮件发送失败，收件人邮箱不合法',
        to: order.contact_email,
        lang: order.lang
      })
    }
    let templateData = template.dataValues
    let html = templateData.content || ''
    let count = order.count
    if (order.ship.code === 'Custom') {
      count = order.userList.length
    }
    html = html.replaceAll('{name}', order.contact_name)
    html = html.replaceAll('{order_no}', order.order_no)
    html = html.replaceAll('{count}', count || '-')
    html = html.replaceAll('{location}', order.ship.location)
    html = html.replaceAll('{start_date}', dayjs(order.start_time).format('YYYY-MM-DD'))
    html = html.replaceAll('{start_time}', dayjs(order.start_time).format('HH:mm'))

    let data = {
      from: templateData.from, // sender address
      to: order.contact_email, // list of receivers
      subject: templateData.subject, // Subject line
      html,
    }
    // 根据订单信息组装模块发送邮件
    // send mail with defined transport object
    const info = await transporter.sendMail(data);
    return this.create({
      ...data,
      order_no: order.order_no,
      message_id: info.messageId,
      content: data.html,
      lang: order.lang
    })
  }

}

module.exports = EmailService;
